import { h, render } from "vue";
import XtxMessage from './message.vue'

type MessageProps = {
  type: 'success' | 'warning' | 'error',
  text: string,
  duration?: number
}

let timer = -1


// 优化(1): 准备一个容器, 存放显示/隐藏的弹框
const divContainer = document.createElement('div')
divContainer.setAttribute('class', 'xtx-message-container')
document.body.appendChild(divContainer)

export default function Message({ type, text, duration = 2000 }: MessageProps) {

  // 创建虚拟dom
  // const vNode = h(XtxMessage, { type }, text)
  const vNode = h(XtxMessage, { type, text })
  // 渲染
  render(vNode, divContainer)

  // 优化(3) : 开启延迟器之前, 先清除
  clearTimeout(timer)
  // 优化(2): 延迟两秒钟, 删除虚拟dom
  timer = window.setTimeout(() => {
    render(null, divContainer)
  }, duration);
}


// 成功
Message.success = function (text: string, duration = 2000) {
  Message({
    type: 'success',
    text,
    duration
  })
}
// 失败
Message.error = function (text: string, duration = 2000) {
  Message({
    type: 'error',
    text,
    duration
  })

}
// 警告
Message.warning = function (text: string, duration = 2000) {
  Message({
    type: 'warning',
    text,
    duration
  })
}
